package main

import (
	"fmt"
	"os"
	"strings"
)

func printItem() {
	fmt.Println("1 收支明细")
	fmt.Println("2 登记收入")
	fmt.Println("3 登记支出")
	fmt.Println("4 退   出")
	fmt.Println("请选择(1-4):")
}
func enterContinue(message ...string) {
	if len(message) > 0 {
		fmt.Printf("%v,按回车键继续", strings.Join(message, ","))
	} else {
		fmt.Println("输入错误,按回车键继续")
	}
	_, err := fmt.Scanln()
	if err != nil {
		enterContinue()
	}
}

func main() {
	fmt.Println("---------------家庭收支记账软件---------------")
	for {
		printItem()
		var item int
		_, err := fmt.Scanln(&item)
		if err != nil {
			enterContinue()
			continue
		}

		switch item {
		case 1:
			if len(records) == 0 {
				enterContinue("还未记录收支明细")
				continue
			}
			fmt.Println("收支\t账户金额\t收支金额\t说明")
			for _, record := range records {
				fmt.Printf("%v\t%v\t%v\t%v\t\n", record.recordType, record.balance, record.money, record.description)
			}
		case 2:
			var money float64
			fmt.Print("请输入收入金额:")
			var _, err = fmt.Scanln(&money)
			if err != nil {
				enterContinue("输入金额错误")
				continue
			}
			var description string
			fmt.Print("请输入收入说明:")
			_, err = fmt.Scanln(&description)
			if err != nil {
				enterContinue("输入收入说明错误")
				continue
			}
			if strings.TrimSpace(description) == "" {
				enterContinue("收入说明不能为空")
				continue
			}
			balance = balance + money
			record := Record{
				money:       money,
				balance:     balance,
				recordType:  income,
				description: description,
			}
			records = append(records, record)

		case 3:
			var money float64
			fmt.Print("请输入支出金额:")
			var _, err = fmt.Scanln(&money)
			if err != nil {
				enterContinue("输入支出金额错误")
				continue
			}

			balance = balance - money
			if balance < 0 {
				enterContinue("余额不足")
				continue
			}

			var description string
			fmt.Print("请输入支出说明:")
			_, err = fmt.Scanln(&description)
			if err != nil {
				enterContinue("输入支出说明错误")
				continue
			}

			if strings.TrimSpace(description) == "" {
				enterContinue("支出说明不能为空")
				continue
			}

			record := Record{
				money:       money,
				balance:     balance,
				recordType:  expenditure,
				description: description,
			}
			records = append(records, record)
		case 4:
			fmt.Println("再见")
			os.Exit(0)
		default:
			fmt.Println("输入错误,按回车键继续")
		}

	}
}
